package com.sdr.locationservice;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by homelajiang on 2016/8/26 0026.
 */
public class LocationService extends Service implements BDLocationListener {
    private LocationClient mLocationClient;
    private int LOCATION_NOTIFY_ID = 222;
    private String reqUrl;
    private String userId;
    private String accessToken;
    private NotificationManager manger;

    @Override
    public void onCreate() {
        super.onCreate();
        manger = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mLocationClient = new LocationClient(getApplicationContext());
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd0911");
        option.setScanSpan(5000);
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        option.setLocationNotify(false);
        option.setIsNeedLocationDescribe(true);
        option.setIsNeedLocationPoiList(false);
        option.setIgnoreKillProcess(false);
        option.SetIgnoreCacheException(true);
        option.setEnableSimulateGps(false);
        mLocationClient.setLocOption(option);
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        boolean isStop = intent.getBooleanExtra("stop", false);

        if (isStop) {
            manger.cancel(LOCATION_NOTIFY_ID);
            stopSelf();
            return START_NOT_STICKY;
        }
        this.userId = intent.getStringExtra("userId");
        this.accessToken = intent.getStringExtra("accessToken");
        this.reqUrl = intent.getStringExtra("url");

        mLocationClient.registerLocationListener(this);
        mLocationClient.start();

//        Notification.Builder builder = new Notification.Builder(this);
//        builder.setSmallIcon(getApplication().getResources().getIdentifier("icon", "drawable", getApplication().getPackageName()))
//                .setTicker("定位服务启动")
//                .setContentTitle("定位服务")
//                .setContentText("定位服务运行中...")
//                .setAutoCancel(false)
//                .setOngoing(true);
//
//        Notification notification = builder.getNotification();
//        manger.notify(LOCATION_NOTIFY_ID, notification);

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
        mLocationClient.unRegisterLocationListener(this);
    }

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {

        if (TextUtils.isEmpty(userId)
                || TextUtils.isEmpty(accessToken) || TextUtils.isEmpty(reqUrl) || !isNetworkConnected()) {
            return;
        }
        Map<String, String> params = new HashMap<String, String>();

        params.put("userId", userId);
        params.put("accessToken", accessToken);
        params.put("locTime", String.valueOf(bdLocation.getTime()));
        params.put("locType", String.valueOf(bdLocation.getLocType()));
        params.put("latitude", String.valueOf(bdLocation.getLatitude()));
        params.put("longitude", String.valueOf(bdLocation.getLongitude()));
        params.put("radius", String.valueOf(bdLocation.getRadius()));

        if (bdLocation.getLocType() == BDLocation.TypeGpsLocation) {
            params.put("altitude", String.valueOf(bdLocation.getAltitude()));
            params.put("direction", String.valueOf(bdLocation.getDirection()));
            params.put("satelliteNumber", String.valueOf(bdLocation.getSatelliteNumber()));
            params.put("speed", String.valueOf(bdLocation.getSpeed()));
            params.put("addrStr", String.valueOf(bdLocation.getAddrStr()));
        } else if (bdLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
            params.put("operators", String.valueOf(bdLocation.getRadius()));
        } else if (bdLocation.getLocType() == BDLocation.TypeOffLineLocation) {

        } else {
            return;
        }

        new uploadAsyTask()
                .execute(params);
    }

    /**
     * 判断是否有网络连接
     *
     * @return
     */
    public boolean isNetworkConnected() {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo != null) {
            return mNetworkInfo.isAvailable();
        }
        return false;
    }

    class uploadAsyTask extends AsyncTask<Map<String, String>, Void, Void> {

        @Override
        protected Void doInBackground(Map<String, String>... paramsMap) {
            URL url;
            Map<String, String> params = paramsMap[0];
            HttpURLConnection con = null;
            PrintWriter printWriter = null;
            BufferedReader bufferedReader = null;
            StringBuilder responseResult = new StringBuilder();
            StringBuilder paramBuffer = new StringBuilder();

            // 组织请求参数
            Iterator it = params.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry element = (Map.Entry) it.next();
                paramBuffer.append(element.getKey());
                paramBuffer.append("=");
                paramBuffer.append(element.getValue());
                paramBuffer.append("&");
            }
            if (paramBuffer.length() > 0) {
                paramBuffer.deleteCharAt(paramBuffer.length() - 1);
            }

            try {
                url = new URL(reqUrl);
                con = (HttpURLConnection) url.openConnection();
                // 设置通用的请求属性
                con.setRequestProperty("accept", "application/json");
                con.setRequestProperty("connection", "Keep-Alive");
                con.setRequestProperty("Content-Length", String
                        .valueOf(paramBuffer.length()));
                con.setRequestMethod("POST");
                // 发送POST请求必须设置如下两行
                con.setDoOutput(true);
                con.setDoInput(true);
                con.setConnectTimeout(10000);
                con.setReadTimeout(2000);

                // 获取URLConnection对象对应的输出流
                printWriter = new PrintWriter(con.getOutputStream());
                // 发送请求参数
                printWriter.write(paramBuffer.toString());
                // flush输出流的缓冲
                printWriter.flush();
                // 根据ResponseCode判断连接是否成功
                int responseCode = con.getResponseCode();
                if (responseCode != 200) {
                    Log.e("", " Error===" + responseCode);
                } else {
                    Log.e("", "Post Success!");
                }
                // 定义BufferedReader输入流来读取URL的ResponseData
                bufferedReader = new BufferedReader(new InputStreamReader(
                        con.getInputStream()));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    responseResult.append("/n").append(line);
                }
                Log.d("result", responseResult.toString());

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (con != null) {
                    con.disconnect();
                }
                try {
                    if (printWriter != null) {
                        printWriter.close();
                    }
                    if (bufferedReader != null) {
                        bufferedReader.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            return null;
        }
    }
}
